package com.magilit.framelibrary.base;


import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.magilit.framelibrary.R;
import com.magilit.framelibrary.annotations.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;


public abstract class FrameBaseActivity extends AppCompatActivity {

    //头部标题栏
    protected RelativeLayout rl_base_title;

    //左item
    protected RelativeLayout item_title_left;
    //中item
    protected RelativeLayout item_title_mid;
    //右item
    protected RelativeLayout item_title_right;


    //是否注册了EventBus
    private boolean isRegisterEventBus = false;

    FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        PgyCrashManager.register(this);
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initContentView();

        rl_base_title = (RelativeLayout) findViewById(R.id.rl_base_title);
        if (showToolBar()) {
            rl_base_title.setVisibility(View.VISIBLE);
        } else {
            rl_base_title.setVisibility(View.GONE);
        }
        item_title_left = (RelativeLayout) findViewById(R.id.item_title_left);
        item_title_mid = (RelativeLayout) findViewById(R.id.item_title_mid);
        item_title_right = (RelativeLayout) findViewById(R.id.item_title_right);
        fragmentManager = getSupportFragmentManager();
        //实际
        onBaseActivityCreated(savedInstanceState);
    }

    protected abstract void initContentView();

    /**
     * 代替onCreate的入口类
     */
    protected abstract void onBaseActivityCreated(Bundle savedInstanceState);


    /**
     * 解析注解，给带有@ViewInject注解的View赋值
     */
    protected void autoInjectViewField() {
        try {
            Class<?> clazz = this.getClass();
            Field[] fields = clazz.getDeclaredFields();//获得Activity中声明的字段
            for (Field field : fields) {
                // 查看这个字段是否有我们自定义的注解类标志的
                if (field.isAnnotationPresent(ViewInject.class)) {
                    ViewInject inject = field.getAnnotation(ViewInject.class);
                    int id = inject.value();
                    if (id > 0) {
                        field.setAccessible(true);
                        field.set(this, findViewById(id));//给我们要找的字段设置值
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册EventBus
     */
    protected final void registerEventBus() {
        EventBus.getDefault().register(this);
        isRegisterEventBus = true;
    }

    @Override
    protected void onDestroy() {
//        PgyCrashManager.unregister();
        if (isRegisterEventBus) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    /**
     * 替换Activity的内容
     *
     * @param fragment    fragment
     * @param isBackStack 是否加入回退栈，如果加入，可以通过isBackStack找出并回退
     */
    protected void replaceFragment(Fragment fragment, String isBackStack, int ResId) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (TextUtils.isEmpty(isBackStack)) {
            //fragmentTransaction.replace(R.id.rootlayout_baseactivity, fragment);
            fragmentTransaction.replace(ResId, fragment);
        } else {
            //fragmentTransaction.replace(R.id.rootlayout_baseactivity, fragment, isBackStack);
            fragmentTransaction.replace(ResId, fragment);
            fragmentTransaction.addToBackStack(isBackStack);
        }
//        KeyBoardUtils.closeKeyboard(context);
        fragmentTransaction.commitAllowingStateLoss();
    }

    //===========导航栏相关==============
    protected abstract boolean showToolBar();

    protected void setToolBarColor(int colorResId) {
        rl_base_title.setBackgroundColor(ContextCompat.getColor(this, colorResId));
    }

    protected void initToolBarLeftItem(int left_icon, View.OnClickListener onClickListener) {

        if (left_icon > 0) {
            ImageView iv_title_left_icon = (ImageView) item_title_left.findViewById(R.id.iv_title_left_icon);
            iv_title_left_icon.setImageResource(left_icon);
        }
        item_title_left.setOnClickListener(onClickListener);
    }

    protected void initToolBarMidItem(int mid_icon, String title, View.OnClickListener onClickListener) {
        if (mid_icon > 0) {
            ImageView iv_title_mid_icon = (ImageView) item_title_mid.findViewById(R.id.iv_title_mid_icon);
            iv_title_mid_icon.setImageResource(mid_icon);
        }
        if (!TextUtils.isEmpty(title)) {
            TextView tv_title_mid = (TextView) item_title_mid.findViewById(R.id.tv_title_mid);
            tv_title_mid.setText(title);
        }
        item_title_mid.setOnClickListener(onClickListener);
    }

    protected void initToolBarRightItem(int right_icon, String right_text, View.OnClickListener onClickListener) {

        if (right_icon > 0) {
            ImageView iv_title_right_icon = (ImageView) item_title_right.findViewById(R.id.iv_title_right_icon);
            iv_title_right_icon.setImageResource(right_icon);
        }

        if (!TextUtils.isEmpty(right_text)) {
            TextView tv_title_right = (TextView) item_title_right.findViewById(R.id.tv_title_right_text);
            tv_title_right.setText(right_text);
        }

        item_title_right.setOnClickListener(onClickListener);

    }

    //==========


    protected void setWindowStatusBarColor(int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(ContextCompat.getColor(this, colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void setFullScreen() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    protected void setFullScreenWithStatus() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT); //也可以设置成灰色透明的，比较符合Material Design的风格
        } else {
            setFullScreen();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
